package com.note.app.controller;

import com.note.app.annotation.LogRecord;
import com.note.app.dto.collaboration.CollaborationOperationDTO;
import com.note.app.dto.collaboration.CollaborationParticipantDTO;
import com.note.app.dto.collaboration.CollaborationSessionDTO;
import com.note.app.service.CollaborationService;
import com.note.common.vo.ResponseVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 协作控制器
 */
@Tag(name = "协作管理", description = "协作会话和操作相关接口")
@RestController
@RequestMapping("/collaboration")
@RequiredArgsConstructor
public class CollaborationController {

    private final CollaborationService collaborationService;

    @Operation(summary = "创建协作会话")
    @Parameters({
            @Parameter(name = "userId", description = "用户ID", required = true),
            @Parameter(name = "noteId", description = "笔记ID", required = true),
            @Parameter(name = "name", description = "会话名称", required = true)
    })
    @PostMapping("/session")
    @LogRecord(description = "创建协作会话", module = "协作管理", operationType = LogRecord.OperationType.CREATE)
    public ResponseVo<CollaborationSessionDTO> createSession(
            @RequestParam Long userId,
            @RequestParam Long noteId,
            @RequestParam String name) {
        CollaborationSessionDTO session = collaborationService.createSession(userId, noteId, name);
        return ResponseVo.success(session);
    }

    @Operation(summary = "关闭协作会话")
    @Parameters({
            @Parameter(name = "sessionId", description = "会话ID", required = true),
            @Parameter(name = "userId", description = "用户ID", required = true)
    })
    @PostMapping("/session/{sessionId}/close")
    @LogRecord(description = "关闭协作会话", module = "协作管理", operationType = LogRecord.OperationType.UPDATE)
    public ResponseVo<Boolean> closeSession(
            @PathVariable Long sessionId,
            @RequestParam Long userId) {
        boolean responseVo = collaborationService.closeSession(sessionId, userId);
        return ResponseVo.success(responseVo);
    }

    @Operation(summary = "加入协作会话")
    @Parameters({
            @Parameter(name = "sessionId", description = "会话ID", required = true),
            @Parameter(name = "userId", description = "用户ID", required = true),
            @Parameter(name = "accessToken", description = "访问令牌", required = true)
    })
    @PostMapping("/session/{sessionId}/join")
    @LogRecord(description = "加入协作会话", module = "协作管理", operationType = LogRecord.OperationType.UPDATE)
    public ResponseVo<CollaborationParticipantDTO> joinSession(
            @PathVariable Long sessionId,
            @RequestParam Long userId,
            @RequestParam String accessToken) {
        CollaborationParticipantDTO participant = collaborationService.joinSession(sessionId, userId, accessToken);
        return ResponseVo.success(participant);
    }

    @Operation(summary = "离开协作会话")
    @Parameters({
            @Parameter(name = "sessionId", description = "会话ID", required = true),
            @Parameter(name = "userId", description = "用户ID", required = true)
    })
    @PostMapping("/session/{sessionId}/leave")
    @LogRecord(description = "离开协作会话", module = "协作管理", operationType = LogRecord.OperationType.UPDATE)
    public ResponseVo<Boolean> leaveSession(
            @PathVariable Long sessionId,
            @RequestParam Long userId) {
        boolean responseVo = collaborationService.leaveSession(sessionId, userId);
        return ResponseVo.success(responseVo);
    }

    @Operation(summary = "获取会话信息")
    @Parameters({
            @Parameter(name = "sessionId", description = "会话ID", required = true)
    })
    @GetMapping("/session/{sessionId}")
    @LogRecord(description = "获取协作会话信息", module = "协作管理", operationType = LogRecord.OperationType.QUERY)
    public ResponseVo<CollaborationSessionDTO> getSessionInfo(
            @PathVariable Long sessionId) {
        CollaborationSessionDTO session = collaborationService.getSessionInfo(sessionId);
        return ResponseVo.success(session);
    }

    @Operation(summary = "获取用户的协作会话列表")
    @Parameters({
            @Parameter(name = "userId", description = "用户ID", required = true)
    })
    @GetMapping("/sessions/user/{userId}")
    @LogRecord(description = "获取用户协作会话列表", module = "协作管理", operationType = LogRecord.OperationType.QUERY)
    public ResponseVo<List<CollaborationSessionDTO>> getUserSessions(
            @PathVariable Long userId) {
        List<CollaborationSessionDTO> sessions = collaborationService.getUserSessions(userId);
        return ResponseVo.success(sessions);
    }

    @Operation(summary = "获取笔记的活跃协作会话")
    @Parameters({
            @Parameter(name = "noteId", description = "笔记ID", required = true)
    })
    @GetMapping("/sessions/note/{noteId}")
    @LogRecord(description = "获取笔记活跃协作会话", module = "协作管理", operationType = LogRecord.OperationType.QUERY)
    public ResponseVo<List<CollaborationSessionDTO>> getNoteActiveSessions(
            @PathVariable Long noteId) {
        List<CollaborationSessionDTO> sessions = collaborationService.getNoteActiveSessions(noteId);
        return ResponseVo.success(sessions);
    }

    @Operation(summary = "获取操作历史")
    @Parameters({
            @Parameter(name = "sessionId", description = "会话ID", required = true),
            @Parameter(name = "limit", description = "限制数量", required = false)
    })
    @GetMapping("/operations/{sessionId}")
    @LogRecord(description = "获取协作操作历史", module = "协作管理", operationType = LogRecord.OperationType.QUERY)
    public ResponseVo<List<CollaborationOperationDTO>> getOperationHistory(
            @PathVariable Long sessionId,
            @RequestParam(defaultValue = "50") int limit) {
        List<CollaborationOperationDTO> operations = collaborationService.getOperationHistory(sessionId, limit);
        return ResponseVo.success(operations);
    }

    @Operation(summary = "更新参与者权限")
    @Parameters({
            @Parameter(name = "sessionId", description = "会话ID", required = true),
            @Parameter(name = "userId", description = "用户ID", required = true),
            @Parameter(name = "participantId", description = "参与者ID", required = true),
            @Parameter(name = "role", description = "角色", required = true)
    })
    @PostMapping("/participant/role")
    @LogRecord(description = "更新协作参与者权限", module = "协作管理", operationType = LogRecord.OperationType.UPDATE)
    public ResponseVo<Boolean> updateParticipantRole(
            @RequestParam Long sessionId,
            @RequestParam Long userId,
            @RequestParam Long participantId,
            @RequestParam int role) {
        boolean responseVo = collaborationService.updateParticipantRole(sessionId, userId, participantId, role);
        return ResponseVo.success(responseVo);
    }

    @Operation(summary = "保存协作内容到笔记")
    @Parameters({
            @Parameter(name = "sessionId", description = "会话ID", required = true),
            @Parameter(name = "userId", description = "用户ID", required = true)
    })
    @PostMapping("/session/{sessionId}/save")
    @LogRecord(description = "保存协作内容到笔记", module = "协作管理", operationType = LogRecord.OperationType.UPDATE)
    public ResponseVo<Boolean> saveToNote(
            @PathVariable Long sessionId,
            @RequestParam Long userId) {
        boolean responseVo = collaborationService.saveToNote(sessionId, userId);
        return ResponseVo.success(responseVo);
    }

    @Operation(summary = "获取会话信息（字符串ID）")
    @Parameters({
            @Parameter(name = "sessionIdStr", description = "会话ID字符串", required = true)
    })
    @GetMapping("/session/str/{sessionIdStr}")
    @LogRecord(description = "通过字符串ID获取协作会话信息", module = "协作管理", operationType = LogRecord.OperationType.QUERY)
    public ResponseVo<CollaborationSessionDTO> getSessionInfoByStringId(
            @PathVariable String sessionIdStr) {
        try {
            // 尝试将字符串转换为Long
            Long sessionId = Long.parseLong(sessionIdStr);
            CollaborationSessionDTO session = collaborationService.getSessionInfo(sessionId);
            return ResponseVo.success(session);
        } catch (NumberFormatException e) {
            return ResponseVo.paramError("会话ID格式不正确，应为数字ID");
        }
    }
    
    @Operation(summary = "加入协作会话（字符串ID）")
    @Parameters({
            @Parameter(name = "sessionIdStr", description = "会话ID字符串", required = true),
            @Parameter(name = "userId", description = "用户ID", required = true),
            @Parameter(name = "accessToken", description = "访问令牌", required = true)
    })
    @PostMapping("/session/str/{sessionIdStr}/join")
    @LogRecord(description = "通过字符串ID加入协作会话", module = "协作管理", operationType = LogRecord.OperationType.UPDATE)
    public ResponseVo<CollaborationParticipantDTO> joinSessionByStringId(
            @PathVariable String sessionIdStr,
            @RequestParam Long userId,
            @RequestParam String accessToken) {
        try {
            // 尝试将字符串转换为Long
            Long sessionId = Long.parseLong(sessionIdStr);
            CollaborationParticipantDTO participant = collaborationService.joinSession(sessionId, userId, accessToken);
            return ResponseVo.success(participant);
        } catch (NumberFormatException e) {
            return ResponseVo.paramError("会话ID格式不正确，应为数字ID");
        }
    }
} 